<template>
    <div id="account_manage">
        <el-tabs :value="tabs.current" type="card" :before-leave="switch_tab">
            <el-tab-pane :label="tabs.account.label" :name="tabs.account.name">
                <el-table ref="account_table" :data="account.tableData"
                          :height="fixedHeight" :max-height="fixedHeight" stripe border highlight-current-row>
                    <el-table-column v-for="(item,index) in account.tableHead"
                                     :label="item.title"
                                     :prop="item.value"
                                     :width="item.width"
                                     align="center"
                                     :key="index">
                        <template slot-scope="scope">
                            <span v-if="item.value === 'status'">{{scope.row.status ? '正常' : '禁用'}}</span>
                            <span v-else>{{scope.row[item.value]}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" size="mini" @click="account_disable(scope.row.id)">
                                {{scope.row.status ? '禁用' : '启用'}}
                            </el-button>
                            <el-button type="text" size="mini" @click="account_curaction(scope.row.id,'reset_pwd')">
                                重置密码
                            </el-button>
                            <el-button type="text" size="mini" @click="account_curaction(scope.row.id,'show_logs')">
                                查看日志
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane :label="tabs.role.label" :name="tabs.role.name">
                <el-table :data="role.tableData" style="width: 100%;" border
                          :max-height="fixedHeight" :height="fixedHeight" highlight-current-row>
                    <el-table-column label="角色名称" prop="name" width="200" align="center"/>
                    <el-table-column label="角色描述" prop="desc" align="center"/>
                    <el-table-column label="操作" width="220" align="center">
                        <template slot="header">
                            <span style="cursor: pointer; color: #409EFF;" @click="role.roleDlg.status = true">新增</span>
                        </template>
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="role_curaction(scope.row, 'role')">修改
                            </el-button>
                            <el-button type="text" size="small" @click="role_del(scope.row.id)">删除</el-button>
                            <el-button type="text" size="small" @click="role_curaction(scope.row, 'account')">帐号
                            </el-button>
                            <el-button type="text" size="small" @click="role_curaction(scope.row, 'permit')">功能
                            </el-button>
                            <el-button type="text" size="small" @click="role_curaction(scope.row, 'dataScope')">数据</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <el-dialog :visible.sync="account.resetPass.dlgStatus" title="重置密码" width="30%">
            <el-form ref="reset_password" :model="account.resetPass.formData" :rules="account.resetPass.formRule"
                     label-width="80px">
                <el-form-item label="新密码：" prop="newpwd">
                    <el-input v-model="account.resetPass.formData.newpwd" show-password/>
                </el-form-item>
                <el-form-item label="请确认：" prop="verpwd">
                    <el-input v-model="account.resetPass.formData.verpwd" show-password/>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="generate_password(8)">生成密码</el-button>
                <el-button @click="account.resetPass.dlgStatus = false">取消</el-button>
                <el-button @click="account_resetpass('reset_password')">确定</el-button>
            </span>
        </el-dialog>
        <el-dialog :visible.sync="account.logs.dlgStatus" title="帐号日志" fullscreen>
            <el-table ref="account_table" :data="account.logs.tableData"
                      stripe border highlight-current-row>
                <el-table-column v-for="(item,index) in account.logs.tableHead"
                                 :label="item.title"
                                 :prop="item.value"
                                 :width="item.width"
                                 align="center"
                                 :key="index" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row[item.value]}}
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <el-dialog :visible.sync="role.roleDlg.status" title="角色" :show-close="false" width="350px">
            <el-form ref="Role_Dialog" :model="role.roleDlg.formData" :rules="role.roleDlg.formRule"
                     size="small" label-width="50px" label-position="right">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="role.roleDlg.formData.name"/>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="role.roleDlg.formData.description"/>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="role.roleDlg.status = false">取 消</el-button>
                <el-button type="primary" @click="role_dlg_submit('Role_Dialog')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog :visible.sync="role.accountDlg.status" title="关联帐号" :show-close="false" width="650px">
            <div style="text-align: center">
                <el-transfer filterable v-model="role.accountDlg.select" :data="role.accountDlg.unselect"
                             style="text-align: left; display: inline-block" :titles="['未选帐号','已选帐号']"/>
            </div>
            <span slot="footer">
                <el-button @click="role.accountDlg.status = false">取 消</el-button>
                <el-button type="primary" @click="role_set_account">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog :visible.sync="role.permitDlg.status" title="角色权限" width="650px">
            <el-row :gutter="8">
                <el-col :span="8">
                    <el-tree :data="role.permitDlg.moduleTree" :props="role.permitDlg.moduleProp"
                             style="height: 300px; border: 1px solid #dadada"
                             @node-click="role_permit_selmodule"/>
                </el-col>
                <el-col :span="16">
                    <el-table :data="role.permitDlg.actions" style="width: 100%;" border height="300" max-height="300"
                              @select="role_permit_selaction" @select-all="role_permit_selaction" ref="Role_PermitDlg">
                        <el-table-column type="selection" width="80" align="center"/>
                        <el-table-column label="名称" prop="name" align="center"/>
                    </el-table>
                </el-col>
            </el-row>
        </el-dialog>
        <el-dialog :visible.sync="role.dataScopeDlg.status" title="数据范围" width="650px">
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "AccountManage",
        computed: {
            fixedHeight() {
                let fixedHeight = this.$store.state.fixedHeight;
                if (fixedHeight !== undefined)
                    fixedHeight = fixedHeight - 56;
                return fixedHeight;
                // return this.$store.state.fixedHeight - 56;
            },
        },
        data() {
            return {
                tabs: {
                    current: 'account',
                    account: {label: '帐号管理', name: 'account'},
                    role: {label: '角色管理', name: 'role'}
                },
                account: {
                    currentID: null,
                    tableHead: [
                        {
                            title: '编号',
                            value: 'id',
                            width: 80
                        },
                        {
                            title: '员工',
                            value: 'emp',
                            width: 120
                        },
                        {
                            title: '帐号',
                            value: 'username',
                            width: 120
                        },
                        {
                            title: '状态',
                            value: 'status',
                            width: 120
                        },
                        {
                            title: '创建时间',
                            value: 'create_time',
                        },
                        {
                            title: '最后登录',
                            value: 'login_time',
                        },
                        {
                            title: '登录地址',
                            value: 'login_ip',
                        }
                    ],
                    tableData: [],
                    resetPass: {
                        dlgStatus: false,
                        formData: {},
                        formRule: {
                            newpwd: [
                                {required: true, message: '请输入新密码！', trigger: 'blur'},
                                {min: 6, message: '密码最少六位', trigger: 'blur'}
                            ],
                            verpwd: [
                                {required: true, message: '请确认新密码！', trigger: 'blur'},
                                {
                                    validator: (rule, value, callback) => {
                                        let newpwd = this.account.resetPass.formData.newpwd;
                                        if (value !== newpwd) {
                                            callback(new Error('两次输入密码不一致'));
                                        } else {
                                            callback()
                                        }
                                    }
                                }
                            ]
                        }
                    },
                    logs: {
                        dlgStatus: false,
                        tableData: [],
                        tableHead: [
                            {
                                title: 'ID',
                                value: 'id',
                                width: 50
                            },
                            {
                                title: '时间',
                                value: 'date',
                                width: 120
                            },
                            {
                                title: '模块',
                                value: 'module',
                                width: 120
                            },
                            {
                                title: '方法',
                                value: 'method',
                                width: 120
                            },
                            {
                                title: '地址',
                                value: 'ipaddr',
                                width: 120
                            },
                            {
                                title: '请求数据',
                                value: 'reqdata',
                            },
                            {
                                title: '响应数据',
                                value: 'resdata',
                            }
                        ]
                    }

                },
                role: {
                    currentID: null,
                    tableData: [],
                    roleDlg: {
                        status: false,
                        formData: {},
                        formRule: {
                            name: {required: true, message: '请输入角色名称！', trigger: 'blur'}
                        }
                    },
                    accountDlg: {
                        status: false,
                        select: [],
                        unselect: []
                    },
                    permitDlg: {
                        status: false,
                        moduleTree: [],
                        moduleProp: {label: 'name', children: 'children'},
                        current_moduleID: null,
                        actions: []
                    },
                    dataScopeDlg: {
                        status: false,
                    }
                }
            }
        },
        methods: {
            switch_tab(current_tab) {
                if (current_tab === 'role')
                    this.role_get_all();
                if (current_tab === 'account')
                    this.account_get_all();
            },
            generate_password(length) {
                length = Number(length);
                // Limit length
                if (length < 6) {
                    length = 6
                } else if (length > 16) {
                    length = 16
                }
                let passwordArray = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '1234567890', '!@#$%&*()'];
                let password = [];
                let n = 0;
                for (let i = 0; i < length; i++) {
                    // If password length less than 9, all value random
                    if (password.length < (length - 4)) {
                        // Get random passwordArray index
                        let arrayRandom = Math.floor(Math.random() * 4);
                        // Get password array value
                        let passwordItem = passwordArray[arrayRandom];
                        // Get password array value random index
                        // Get random real value
                        let item = passwordItem[Math.floor(Math.random() * passwordItem.length)];
                        password.push(item);
                    } else {
                        // If password large then 9, lastest 4 password will push in according to the random password index
                        // Get the array values sequentially
                        let newItem = passwordArray[n];
                        let lastItem = newItem[Math.floor(Math.random() * newItem.length)];
                        // Get array splice index
                        let spliceIndex = Math.floor(Math.random() * password.length);
                        password.splice(spliceIndex, 0, lastItem);
                        n++
                    }
                }
                this.$set(this.account.resetPass.formData, "newpwd", password.join(""));
                this.$set(this.account.resetPass.formData, "verpwd", password.join(""));
            },
            account_get_all() {
                this.api_interface('account.get.all')
                    .then(res => {
                        if (res.code === '0x00010') {
                            this.account.tableData = res.data;
                        }
                    })
            },
            account_disable(id) {
                this.api_interface('account.disable', {id: id})
                    .then(res => {
                        if (res.code === '0x00018') {
                            this.$message.success(res.msg);
                            this.account_get_all();
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
            },
            account_curaction(id, dlg) {
                this.account.currentID = id;
                if (dlg === 'reset_pwd')
                    this.account.resetPass.dlgStatus = true;
                if (dlg === 'show_logs') {
                    this.api_interface('account.showlogs', {id: id})
                        .then(res => {
                            if (res.code === '0x00010') {
                                this.account.logs.tableData = res.data;
                                this.account.logs.dlgStatus = true;
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                }
            },
            account_resetpass(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        this.api_interface('account.resetpass', this._.assign({id: this.account.currentID}, this.account.resetPass.formData))
                            .then(res => {
                                if (res.code === '0x00016') {
                                    this.$message.success(res.msg);
                                    this.account.resetPass.formData = {};
                                    this.account.resetPass.dlgStatus = false;
                                } else {
                                    this.$message.error(res.msg);
                                }
                            })
                    }
                })
            },
            role_get_all() {
                this.api_interface('role.get.all')
                    .then(res => {
                        if (res.code === '0x00010') {
                            this.role.tableData = res.data;
                        }
                    })
            },
            role_dlg_submit(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        if (this._.has(this.role.roleDlg.formData, 'id')) {     // 修改
                            this.api_interface('role.chg', this.role.roleDlg.formData)
                                .then(res => {
                                    if (res.code === '0x00016') {
                                        this.$message.success(res.msg);
                                        this.role.roleDlg.status = false;
                                        this.role.roleDlg.formData = {};
                                        this.role_get_all();
                                    } else {
                                        this.$message.error(res.msg);
                                    }
                                })
                        } else {    // 新增
                            this.api_interface('role.add', this.role.roleDlg.formData)
                                .then(res => {
                                    if (res.code === '0x00012') {
                                        this.$message.success(res.msg);
                                        this.role.roleDlg.status = false;
                                        this.role.roleDlg.formData = {};
                                        this.role_get_all();
                                    } else {
                                        this.$message.error(res.msg);
                                    }
                                })
                        }
                    }
                })
            },
            role_curaction(row, dlg) {
                this.role.currentID = row.id;
                if (dlg === 'role') {
                    this.role.roleDlg.formData = row;
                    this.role.roleDlg.status = true;
                }
                if (dlg === 'account') {
                    this.api_interface('role.account.get', {id: row.id})
                        .then(res => {
                            if (res.code === '0x00010') {
                                this.role.accountDlg.select = res.data.sel;
                                this.role.accountDlg.unselect = res.data.all;
                                this.role.accountDlg.status = true;
                            }
                        })
                }
                if (dlg === 'permit') {
                    this.role.permitDlg.actions = [];
                    this.api_interface('role.permit.module')
                        .then(res => {
                            if (res.code === '0x00010') {
                                this.role.permitDlg.moduleTree = res.data;
                                this.role.permitDlg.status = true;
                            }
                        })
                }
                if (dlg === 'dataScope') {
                    this.role.dataScopeDlg.status = true;
                }
            },
            role_del(id) {
                this.api_interface('role.del', {id: id})
                    .then(res => {
                        if (res.code === '0x00014') {
                            this.$message.success(res.msg);
                            this.role_get_all();
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
            },
            role_set_account() {
                this.api_interface('role.account.set', {id: this.role.currentID, select: this.role.accountDlg.select})
                    .then(res => {
                        if (res.code === '0x00016') {
                            this.$message.success(res.msg);
                            this.role.accountDlg.status = false;
                        }
                    })
            },
            role_permit_selmodule(node) {
                this.role.permitDlg.current_moduleID = node.id;
                if (node.type === '模块') {
                    this.api_interface('role.get.permit.action', {module_id: node.id, role_id:this.role.currentID})
                        .then(res => {
                            if (res.code === '0x00010') {
                                this.role.permitDlg.actions = res.data.all;
                                this.$nextTick(function () {
                                    if (res.data.sel.length > 0) {
                                        res.data.sel.forEach(sel => {
                                            this.role.permitDlg.actions.forEach(all => {
                                                if (sel.id === all.id) {
                                                    this.$refs.Role_PermitDlg.toggleRowSelection(all);
                                                }
                                            })
                                        })
                                    }
                                })
                            }
                        })
                }
            },
            role_permit_selaction(selection) {
                let actions = [];
                for (let i=0; i < selection.length; i++) {
                    actions.push(selection[i].id)
                }
                this.api_interface('role.set.permit.action', {role_id:this.role.currentID, module_id: this.role.permitDlg.current_moduleID, actions:actions})
                    .then(res => {
                        if (res.code === '0x00016') {
                            this.$message.success(res.msg);
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
            }
        },
        mounted() {
            this.account_get_all();
        }
    }
</script>

<style scoped lang="stylus">
    #account_manage {
        background-color white
    }
</style>